package com.Tcat.upload.service;

import com.Tcat.upload.config.UploadProperties;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.tcat.common.enums.ExceptionEnum;
import com.tcat.common.exception.TcatException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {
    @Autowired
    private UploadProperties prop;
    private static final List<String> ALLOW_TYPES= Arrays.asList("image/jpeg","image/png","image/bmp","image/jpg");

    private static final Logger LOGGGER= LoggerFactory.getLogger(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadImage(MultipartFile file) {
        try {
            String originalFilname = file.getOriginalFilename();
            //校验文件类型
            String contentType =file.getContentType();
            if(!ALLOW_TYPES.contains(contentType)){
                throw new TcatException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image == null ){
                System.out.println("文件内容");
                throw new TcatException(ExceptionEnum.INVALID_FILE_TYPE);
            }

            //保存文件到本地
            File dest=new File("F:\\Download\\protices",file.getOriginalFilename());
            file.transferTo(dest);
            //返回路径
            return "http://image.tcat.com/"+file.getOriginalFilename();
            //String ext= StringUtils.substringAfterLast(originalFilname,".");
            //StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //return "http://image.tcat.com/"+storePath.getFullPath();
        } catch (IOException e) {
            //上传失败
            log.error("上传文件失败",e);
            throw new TcatException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }

}
